<template>
  <ContainerGroup>
    <Container style="margin-bottom: 10px">
      <FilterForm
        ref="filterForm"
        :elements="filterElements"
        @submit="handleSearch"
        @reset="resetForm"
      />
    </Container>
    <Container
      height="fill"
      :scroll-y="true"
      display="flexY"
      style="position: relative"
    >
      <OperationContainer
        style="margin-bottom: 10px; display: flex; align-items: center"
      >
        <Button icon="add" @click="handleAdd">新增</Button>
        <div>
          <Button icon="search" @click="handleKdDept">开单科室未关联</Button>
        </div>
        <div>
          <Button icon="search" @click="handleZxDept">执行科室未关联</Button>
        </div>
      </OperationContainer>
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        border
        :header-cell-style="{ background: '#fafafa', borderColor: '#e7ecf8' }"
        header-row-class-name="ck-table-header"
        row-class-name="ck-table-row"
        size="small"
        height="100%"
      >
        <el-table-column align="center" type="index" label="" width="60" />
        <!-- <el-table-column type="selection" width="55" /> -->
        <el-table-column label="年/月">
          <template v-slot="scope">
            {{ scope.row.year + "-" + scope.row.month }}
          </template>
        </el-table-column>
        <el-table-column prop="billDeptCode" label="开单科室编号" />
        <el-table-column prop="billDeptName" label="开单科室" />
        <el-table-column prop="executiveDeptCode" label="执行科室编号" />
        <el-table-column prop="executiveDeptName" label="执行科室" />
        <el-table-column label="收费类别名称">
          <template v-slot="scoped">
            {{
              scoped.row.type == 1
                ? "住院收入"
                : scoped.row.type == 2
                ? "门诊收入"
                : scoped.row.type == 3
                ? "非HIS收入"
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column prop="feeName" label="收入项目" />
        <el-table-column label="金额">
          <template v-slot="scope">
            {{ scope.row.amount && Number(scope.row.amount).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="摘要" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <i
            v-if="scope.row.extraE ==1"
              class="el-icon-edit-outline"
              style="
                padding-top: 4px;
                font-size: 20px;
                color: #207efa;
                cursor: pointer;
              "
              @click="handleEdit(scope.row)"
            />
            <i
             v-if="scope.row.extraE ==1"
              class="el-icon-delete"
              style="
                padding-top: 4px;
                padding-left: 10px;
                font-size: 20px;
                color: #207efa;
                cursor: pointer;
              "
              @click="handleDelete(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <!-- 合计 -->
      <div class="tb-hj">总额：{{ amount }}</div>
      <!-- 分页 -->
      <Pagination
        :total="pageAttr.total"
        :page="pageAttr.currentPage"
        :page-size="pageAttr.pageSize"
        @pagation="pagationChange"
      />
    </Container>

    <Container>
      <Dialog
        :title="title"
        :visible="showEidtVlidate"
        :footer-btns="[
          {
            text: '保存',
            type: 'primary',
            trigger: 'confirm',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @cancel="drawClose"
        @confirm="handleConfirm"
      >
        <el-form ref="form" :model="formInfo" label-width="80px" size="small">
          <el-row>
            <el-col :span="12">
              <el-form-item label="开单科室">
                <el-select
                  v-model="formInfo.billDeptCode"
                  placeholder="请选择"
                  filterable
                >
                  <el-option
                    v-for="item in filterElements[2].options"
                    :key="item.deptCode"
                    :label="item.deptName"
                    :value="item.deptCode"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="执行科室">
                <el-select
                  v-model="formInfo.executiveDeptCode"
                  placeholder="请选择"
                  filterable
                >
                  <el-option
                    v-for="item in filterElements[2].options"
                    :key="item.deptCode"
                    :label="item.deptName"
                    :value="item.deptCode"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="收费类别">
                <el-select
                  v-model="formInfo.type"
                  placeholder="请选择"
                  filterable
                >
                  <el-option
                    v-for="item in filterElements[1].options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="收入项目">
                <el-select
                  v-model="formInfo.feeCode"
                  placeholder="请选择"
                  filterable
                >
                  <el-option
                    v-for="item in filterElements[4].options"
                    :key="item.edCode"
                    :label="item.edName"
                    :value="item.edCode"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="金额">
                <el-input v-model="formInfo.amount"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="摘要">
                <el-input v-model="formInfo.description"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
             <el-col :span="12">
              <el-form-item label="日期">
                <el-date-picker
                  v-model="formInfo.time"
                  type="date"
                  value-format="yyyy-MM-dd" 
                  format='yyyy-MM-dd'
                  placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </Dialog>
      <!-- 显示执行科室、开单科室未关联 -->
      <Dialog
        :title="gltitle"
        :visible="glVisible"
        :footer-btns="[
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @cancel="() => (glVisible = false)"
      >
        <el-table
          v-loading="glTableLoading"
          :data="glTableData"
          border
          :header-cell-style="{ background: '#fafafa', borderColor: '#e7ecf8' }"
          header-row-class-name="ck-table-header"
          row-class-name="ck-table-row"
          size="small"
          height="30VH"
          style="width: 500px"
        >
          <el-table-column align="center" type="index" label="" width="60" />
          <el-table-column prop="operDtime" width="120" label="年/月" />
          <el-table-column
            prop="billHisCode"
            v-if="gltitle == '开单科室未关联'"
            label="开单科室HIS编号"
          />
          <el-table-column
            v-else
            prop="executiveHisCode"
            label="执行科室HIS编号"
          />
        </el-table>
      </Dialog>
    </Container>
  </ContainerGroup>
</template>

<script>
import Container from "../../../components/Container.vue";
import { Multirole } from "../../../utils/integrate";
import {
  listEtlInComeSource,
  listEnumDetail,
  getUnLinkHisCodeWithBill,
  getUnLinkHisCodeWithExecutive,
} from "../../../utils/apis/dataExchange/index";
import { getDepartmentSource,addBaseInCome,deleteIncomData } from "../../../utils/apis/accountingUnit/share.js";
import { BasicParams } from "../../../utils/basicParams";
import { IncomEntity } from "../../../utils/basicSetting/incomEntity";
export default {
  name: "Wage", // 科室-工资对应
  components: { Container },
  data() {
    return {
      glVisible: false,
      gltitle: "",
      amount: 0,
      title: "",
      deptDataList: [],
      formInfo: {
        billDeptCode: '',
        executiveDeptCode: '',
        type: '',
        feeCode: '',
        amount: '',
        description: '',
        time: ''
      },
      oldTime: '',
      pageAttr: {
        pageSize: 20,
        currentPage: 1,
        total: 0,
      },
      newParamList: {},
      showEidtVlidate: false,
      drawerTitle: "",
      filterElements: [
        {
          key: "yearMonth",
          type: "date-picker",
          label: "年/月",
          mode: "month",
          type: "date-picker",
          format: "yyyy-MM",
          value: this.$util.currentDate(),
          width: 210,
        },
        {
          clearable: true,
          filterable: true,
          key: "type",
          type: "Select",
          label: "收费类型",
          value: "",
          width: 210,
          itemLabel: "label",
          itemValue: "value",
          options: [
            {
              label: "住院收入",
              value: "1",
            },
            {
              label: "门诊收入",
              value: "2",
            },
            {
              label: "非HIS收入",
              value: "3",
            },
          ],
        },
        {
          filterable: true,
          clearable: true,
          key: "billDeptCode", 
          type: "Select",
          label: "开单科室",
          value: "",
          itemLabel: "deptName",
          itemValue: "deptCode",
          width: 210,
          multiple: true,
          collapseTags: true,
          options: [],
        },
        {
          filterable: true,
          clearable: true,
          key: "executiveDeptCode",
          type: "Select",
          label: "执行科室",
          value: "",
          width: 210,
          itemLabel: "deptName",
          itemValue: "deptCode",
          multiple: true,
          collapseTags: true,
          options: [],
        },
        {
          filterable: true,
          clearable: true,
          key: "feeCode",
          type: "Select",
          label: "收入项目",
          value: "",
          itemLabel: "edName",
          itemValue: "edCode",
          width: 210,
          options: [],
        },
        {
          clearable: true,
          filterable: true,
          key: "linkFlag",
          type: "Select",
          label: "是否关联",
          value: "",
          width: 210,
          itemLabel: "label",
          itemValue: "value",
          options: [
            {
              label: "已关联",
              value: "1",
            },
            {
              label: "未关联",
              value: "0",
            },
          ],
        },
      ],
      total: 0,
      pageSize: 20,
      currentPage: 1,
      tableData: [],
      tableLoading: false,
      glTableData: [],
      glTableLoading: false,
    };
  },
  created() {
    // this.getYearMonthList();
    this.getHsSelect();
  },
  mounted() {},
  methods: {
    handleKdDept() {
      this.gltitle = "开单科室未关联";
      this.glVisible = true;
      this.handleSearchWgl(1);
    },
    handleZxDept() {
      this.gltitle = "执行科室未关联";
      this.glVisible = true;
      this.handleSearchWgl(2);
    },
    handleSearchWgl(type) {
      let currentYm =
        this.$refs.filterForm.getParms() &&
        this.$refs.filterForm.getParms().yearMonth;
      let curMonthLastDay = new Date(
        currentYm && currentYm.split("-")[0],
        currentYm && currentYm.split("-")[1],
        0
      );
      // 列表
      let incomEntity = new IncomEntity();
      incomEntity.starTime =
        (currentYm && currentYm + "-" + "01 00:00:00") || "";
      incomEntity.endTime =
        (currentYm &&
          currentYm + "-" + curMonthLastDay.getDate() + " 23:59:59") ||
        "";
      this.glTableLoading = true;
      this.glTableData = [];
      if (type == 1) {
        getUnLinkHisCodeWithBill(incomEntity).then((res) => {
          this.glTableLoading = false;
          if (res.data.code == 200) {
            this.glTableData = res.data.data;
          }
        });
      } else {
        getUnLinkHisCodeWithExecutive(incomEntity).then((res) => {
          this.glTableLoading = false;
          if (res.data.code == 200) {
            this.glTableData = res.data.data;
          }
        });
      }
    },
    getHsSelect() {
      // 科室
      getDepartmentSource({
        projectId: "1",
        SysId: "Cost",
      }).then(async (res) => {
        if (res.data.code === 200) {
          this.filterElements[2].options = res.data.data;
          this.filterElements[3].options = res.data.data;
        }
      });
      //收入项目
      let basicParams = new BasicParams();
      basicParams.edParentCode = "BD_IncomeItem";
      listEnumDetail(basicParams).then(async (res) => {
        if (res.data.code === 200) {
          this.filterElements[4].options = res.data.data;
        }
      });
    },
    getYearMonthList() {
      listYearAndMonth().then((res) => {
        if (res.data.code === 200) {
          this.filterElements[0].options = res.data.data;
          this.dateList = res.data.data;
          this.$nextTick(() => {
            this.initYearMonth = res.data.data[0].value;
            this.filterElements[0].value = res.data.data[0].value;
          });
        }
      });
    },
    getData() {
      let curMonthLastDay = new Date(
        this.newParamList.yearMonth &&
          this.newParamList.yearMonth.split("-")[0],
        this.newParamList.yearMonth &&
          this.newParamList.yearMonth.split("-")[1],
        0
      );

      // 列表
      let incomEntity = new IncomEntity();
      // incomEntity.starTime =
      //   (this.newParamList.yearMonth &&
      //     this.newParamList.yearMonth + "-" + "01 00:00:00") ||
      //   "";
      // incomEntity.endTime =
      //   (this.newParamList.yearMonth &&
      //     this.newParamList.yearMonth +
      //       "-" +
      //       curMonthLastDay.getDate() +
      //       " 23:59:59") ||
      //   "";
      incomEntity.year = new Date(this.newParamList.yearMonth).getFullYear();
      incomEntity.month = new Date(this.newParamList.yearMonth).getMonth() + 1;
      incomEntity.type = this.newParamList.type;
      incomEntity.billDeptCodeList = this.newParamList.billDeptCode || [];
      // incomEntity.billDeptCode = this.newParamList.billDeptCode
      incomEntity.executiveDeptCodeList =
        this.newParamList.executiveDeptCode || [];
      incomEntity.feeCode = this.newParamList.feeCode;
      incomEntity.pageNum = this.pageAttr.currentPage;
      incomEntity.pageSize = this.pageAttr.pageSize;
      incomEntity.linkFlag = this.newParamList.linkFlag || "";
      this.tableLoading = true;
      listEtlInComeSource(incomEntity).then((res) => {
        if (res.data.code === 200) {
          this.tableLoading = false;
          this.tableData = res.data.data.data.list;
          this.pageAttr.total = res.data.data.data.total || 0;
          this.amount = this.fmoney(res.data.data.amount, 2);
        }else{
           this.tableLoading = false;
        }
      });
    },
    fmoney(s, n) {
      n = n > 0 && n <= 20 ? n : 2;
      s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
      var l = s.split(".")[0].split("").reverse(),
        r = s.split(".")[1];
      let t = "";
      for (let i = 0; i < l.length; i++) {
        t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length ? "," : "");
      }
      return t.split("").reverse().join("") + "." + r;
    },
    handleSearch(value) {
      this.newParamList = value;
      this.pageAttr.currentPage = 1;
      this.getData();
    },
    handleDelete(row) {
      //删除
      this.$confirm({
        title: "温馨提示",
        content: "您确定要删除该条数据?",
        okText: "确定",
        cancelText: "取消",
        okFn: () => {
          deleteIncomData(row.id,row.year).then((res) => {
            if (res.data.code === 200) {
              this.$message.success(res.data.message);
              this.pageAttr.currentPage = 1;
              this.getData();
            } else {
              this.$message.error(res.data.message);
            }
          });
        },
        cancelFn: () => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        },
      });
    },
    handleEdit(row) {
      this.handleClearForm();
      this.rowId = row.id;
      this.title = "编辑收入数据";
      this.showEidtVlidate = true;
      this.setDetails(row)
    },
    setDetails(result){
      this.formInfo.billDeptCode = result.billDeptCode
      this.formInfo.executiveDeptCode = result.executiveDeptCode
      this.formInfo.feeCode = result.feeCode
      this.formInfo.amount = result.amount
      this.formInfo.type = result.type + ''
      this.formInfo.time = result.operDtime
      this.oldTime = result.operDtime
      this.formInfo.description = result.description
    },
    handleClearForm() {
      //清除新增/编辑form
      this.formInfo.billDeptCode = "";
      this.formInfo.executiveDeptCode = "";
      this.formInfo.feeCode = "";
      this.formInfo.amount = "";
      this.formInfo.type = "";
      this.formInfo.time = "";
      this.formInfo.description = "";
      this.oldTime = ''
    },
    handleAdd() {
      //新增
      this.handleClearForm();
      this.title = "新增收入数据";
      this.showEidtVlidate = true;
    },
    handleConfirm() {
      //确定
      if (! this.formInfo.billDeptCode) {
        this.$message.warning("请选择开单科室");
        return;
      }
      if (!this.formInfo.executiveDeptCode) {
        this.$message.warning("请选择执行科室");
        return;
      }
       if (!this.formInfo.type) {
        this.$message.warning("请选择收费类别");
        return;
      }

       if (!this.formInfo.feeCode) {
        this.$message.warning("请选择收入项目");
        return;
      }
       if (!this.formInfo.time) {
        this.$message.warning("请选择时间");
        return;
      }
      const param = {
          "billDeptCode": this.formInfo.billDeptCode,
          "billDeptName": this.filterElements[2].options.find(item => item.deptCode === this.formInfo.billDeptCode)?.deptName,
          "executiveDeptCode":  this.formInfo.executiveDeptCode,
          "executiveDeptName": this.filterElements[2].options.find(item => item.deptCode === this.formInfo.executiveDeptCode)?.deptName,
          "feeCode": this.formInfo.feeCode,
          "feeName": this.filterElements[4].options.find(item => item.edCode === this.formInfo.feeCode)?.edName ,
          "amount": this.formInfo.amount,
          "type": this.formInfo.type,
          "time": this.formInfo.time,
          "description": this.formInfo.description
        }
        if(this.title=='编辑收入数据'){
          param.oldTime = this.oldTime
          param.id=this.rowId
        }
       addBaseInCome(param).then((res) => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message);
            this.showEidtVlidate = false;
            //this.getYearMonthList();
            this.getData();
          } else {
            this.$message.error(res.data.message);
          }
        });
    },
    drawClose() {
      this.showEidtVlidate = false;
    },
    resetForm() {
      location.reload();
    },
    // 分页
    pagationChange(payload) {
      console.log("payload", payload);
      this.pageAttr.currentPage = payload.page;
      this.pageAttr.pageSize = payload.pageSize;
      this.getData();
    },
  },
};
</script>

<style lang="less" scoped>
.tb-hj {
  height: 37px;
  // border: 1px solid #ebeef5;
  position: absolute;
  bottom: 18px;
}
.el-table--mini,
.el-table--small,
.el-table__expand-icon {
  font-size: 14px !important;
}

.ck-table-header {
  th {
    background: #fafafa !important;
    height: 48px;
    color: #555555 !important;
  }
}
.pagenation-box {
  display: flex;
  padding-top: 2px;
  justify-content: flex-end;
}
</style>
